package com.hxc.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hxc.common.core.domain.AjaxResult;
import com.hxc.common.enums.UserStatus;
import com.hxc.common.exception.BaseException;
import com.hxc.common.utils.sign.RsaUtils;
import com.hxc.enums.WarantTypes;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.hxc.common.constant.Constants;
import com.hxc.common.core.domain.entity.SysUser;
import com.hxc.common.core.domain.model.LoginUser;
import com.hxc.common.core.redis.RedisCache;
import com.hxc.common.exception.CustomException;
import com.hxc.common.exception.user.CaptchaException;
import com.hxc.common.exception.user.CaptchaExpireException;
import com.hxc.common.exception.user.UserPasswordNotMatchException;
import com.hxc.common.utils.DateUtils;
import com.hxc.common.utils.MessageUtils;
import com.hxc.common.utils.ServletUtils;
import com.hxc.common.utils.ip.IpUtils;
import com.hxc.framework.manager.AsyncManager;
import com.hxc.framework.manager.factory.AsyncFactory;
import com.hxc.system.service.ISysConfigService;
import com.hxc.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 * 
 * @author hxc
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPermissionService permissionService;

    @Value("${config.we-chat.app-id}")
    private String appId;

    @Value("${config.we-chat.app-secret}")
    private String appSecret;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff)
        {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            //ras解密
            password = RsaUtils.decryptByPrivateKey(password);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user)
    {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public AjaxResult weakLogin(String username, String password) {
       Map<String, Object> map = new HashMap<>();
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        String token = tokenService.createToken(loginUser);
        map.put(Constants.TOKEN, token);
        map.put(Constants.JWT_USER, loginUser.getUser());
        return AjaxResult.success("success", map);
    }

    /**
     * 功能描述: 微信授权登录
     * @author yzj
     */
    public AjaxResult wxGrantLogin(String openid){
        Map<String, Object> map = new HashMap<>();
        SysUser user = userService.findGrantLogin(openid);
        if (ObjectUtils.isEmpty(user))
        {
            throw new UsernameNotFoundException("登录用户不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            throw new BaseException("对不起，您的账号已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            throw new BaseException("对不起，您的账号已停用");
        }
        LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
        recordLoginInfo(loginUser.getUser());
        // 生成token
        String token = tokenService.createToken(loginUser);
        map.put(Constants.TOKEN, token);
        map.put(Constants.JWT_USER, loginUser.getUser());
        return AjaxResult.success("success", map);
    }

    /**
     * 功能描述: 获取微信用户信息
     * @author yzj
     */
    public AjaxResult saveUserByOpenId(String code) {
        String URL = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" +
                appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        //获取微信用户授权标识
        JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get(URL));
        if (jsonObject != null) {
            String openId = jsonObject.getString("openid");
            String accessToken = jsonObject.getString("access_token");
            //根据openId查询用户信息
            SysUser user = userService.findGrantLogin(openId);
            if (ObjectUtils.isNotEmpty(user)) {
                String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
                requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
                //获取微信用户信息
                JSONObject resultData = JSONObject.parseObject(HttpUtil.get(requestUrl));
                user = new SysUser();
                user.setOpenid(openId);
                user.setNickName(resultData.getString("nickname"));
                user.setSex(resultData.getString("sex"));
                user.setAvatar(resultData.getString("headimgurl"));
                //默认未完善账户信息
                user.setWxWarant(WarantTypes.no.getCode());
                int result = userService.insertUser(user);
                if (result > 0) {
                    return AjaxResult.success("success", openId);
                } else {
                    return AjaxResult.error("微信用户信息绑定失败");
                }
            } else {
                return AjaxResult.success("success", openId);
            }
        } else {
            return AjaxResult.error("获取微信Openid失败");
        }
    }

}
